<template>
  <!-- 商品名称 -->

  <div>
    <el-card class="box-card">
      <el-form
        :model="formData"
        ref="elForm"
        :rules="rules"
        label-width="100px"
        :label-position="labelPosition"
      >
        <el-form-item label="商品名称:" prop="productname">
          <el-input v-model="formData.productname"></el-input>
        </el-form-item>

        <el-form-item label="商品分类" prop="classification">
          <el-select
            clearable
            v-model="formData.classification"
            placeholder="请选择"
          >
            <el-option
              v-for="item in classifyList"
              :key="item.id"
              :label="item.className"
              :value="item.className"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品仓库" prop="warehouse">
          <el-select
            clearable
            v-model="formData.warehouse"
            placeholder="请选择"
          >
            <el-option
              v-for="item in WarehouseList"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.warehouseName"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数量:" prop="quantity">
          <el-input v-model="formData.quantity"></el-input>
        </el-form-item>

        <el-form-item label="基本价格:" prop="basicprice">
          <el-input v-model="formData.basicprice"></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card-specification">
      <el-form
        :model="formsData"
        ref="elsForm"
        :rules="ruless"
        :label-position="labelPosition"
      >
        <el-form-item label="商品规格:">
          <div
            class="pct-property"
            v-for="(pty, index) in propertyList"
            :key="pty.id"
          >
            <el-form-item label="属性" prop="property">
              <el-select
                clearable
                v-model="pty.propertyName"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in productPropertyList"
                  :key="item.id"
                  :label="item.propertyName"
                  :value="item.propertyName"
                >
                </el-option>
              </el-select>
              <el-button
                class="delete-property"
                @click="removeProperty(index)"
                type="danger"
                icon="el-icon-delete"
                circle
              ></el-button>
            </el-form-item>

            <el-form-item label="属性值:" prop="price" :key="pty.id">
              <!-- 标签 -->
              <el-tag
                :key="tag.value"
                v-for="tag in pty.propertyValues"
                closable
                :disable-transitions="false"
                @close="handleClose(tag, index)"
              >
                {{ tag.value }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="pty.inputVisible"
                v-model="inputValue"
                :ref="'saveTagInput' + pty.id"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm(index)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(index, $event)"
                >+ 添加属性值</el-button
              >
            </el-form-item>
            <el-form-item label="属性值价格:" prop="price">
              <el-input
                v-for="p in pty.propertyValues"
                :key="p.value"
                v-model="p.price"
                :placeholder="p.value"
                class="price-right"
              ></el-input>
            </el-form-item>
          </div>
          <el-button class="add-property" type="primary" @click="addAttr()"
            >添加属性</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card-particulars">
      <el-form ref="elsForms" label-position="labelPosition">
        <el-form-item label="商品封面图:">
          <upload-picture
            @fileNameEvn="getProcuctFileName"
            @removeFileEvn="removefilePct"
            :files="productFiles"
            :limit="8"
          ></upload-picture>
        </el-form-item>

        <el-form-item label="商品详情(图片):">
          <upload-picture
            @fileNameEvn="getFileName"
            @removeFileEvn="removeFile"
            :files="files"
            :limit="limit"
          ></upload-picture>
        </el-form-item>
      </el-form>
    </el-card>

    <div>
      <el-button class="add-property" type="primary" @click="submitProduct"
        >添加商品</el-button
      >
      <input v-model="iddd" type="text" placeholder="id" />
      <el-button class="add-property" type="primary" @click="xgImg"
        >修改商品图片</el-button
      >
    </div>
  </div>
</template>

<script>
import uploadPicture from '../../components/UploadPicture'
import {
  getCommoodityClass,
  getWarehouse,
  getProductPropertyList,
  addProduct,
  upProductImg
} from '../../api/commodity'
export default {
  components: {
    uploadPicture
  },
  data () {
    return {
      iddd: 0,
      id: 1,
      propertyList: [
        {
          id: 1,
          propertyName: '',
          inputVisible: false,
          propertyValues: []
        }
      ],
      // 商品封面图
      productFiles: [],

      // 详情图片最大上传数量
      limit: 5,
      // 详情图片列表（aa.jpg)
      files: [],

      // 标签
      dynamicTags: ['标签一', '标签二'],
      inputValue: '',
      labelPosition: 'left',
      classifyList: [], // 品类列表
      WarehouseList: [], // 仓库列表
      productPropertyList: [], // 商品属性列表
      options: [],
      AttrList: [],

      rules: {
        classification: [
          {
            required: true,
            message: '商品分类不能为空',
            trigger: ['blur']
          }
        ],
        warehouse: [
          {
            required: true,
            message: '商品仓库不能为空',
            trigger: ['blur']
          }
        ]
      },
      // 商品名称
      formData: {
        productname: '',
        classification: '',
        warehouse: '',
        quantity: '',
        basicprice: ''
      },
      // 商品规格
      formsData: {
        property: '',
        price: ''
      },
      ruless: {
        property: [
          {
            required: true,
            message: '商品属性不能为空',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  mounted () {
    // 获取商品分类列表
    getCommoodityClass()
      .then((res) => {
        this.classifyList = res.data.data
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })
    // 获取仓库列表
    getWarehouse()
      .then((res) => {
        this.WarehouseList = res.data.data
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })

    // 获取商品属性列表
    getProductPropertyList()
      .then((res) => {
        this.productPropertyList = res.data.data
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })
  },
  methods: {
    // 修改商品图片
    xgImg () {
      upProductImg(this.iddd, {
        coverPicture: this.productFiles.join(' '),
        introduction: this.files.join(' ')
      }).then((res) => {
        console.log(res)
        this.$message.success('ok')
        this.productFiles = []
        this.files = []
      })
    },
    // 添加商品
    submitProduct () {
      const product = {
        productName: this.formData.productname,
        className: this.formData.classification,
        warehouseName: this.formData.warehouse,
        addNumber: parseInt(this.formData.quantity),
        price: parseFloat(this.formData.basicprice),
        properties: this.propertyList,
        coverPicture: this.productFiles.join(' '),
        introduction: this.files.join(' ')
      }
      if (
        product.productName.trim().length > 0 &&
        product.classification.trim().length > 0 &&
        product.warehouse.trim().length > 0 &&
        product.addNumber.trim().length > 0 &&
        product.price.trim().length > 0 &&
        product.properties.trim().length > 0 &&
        product.coverPicture.trim().length > 0 &&
        product.introduction.trim().length > 0
      ) {
        addProduct(product)
          .then((res) => {
            this.$message.success('添加成功')
            console.log(res)
            this.clearProduct()
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        this.$message.error('添加失败，请检查未填项')
      }
    },
    clearProduct () {
      this.formData.productname = ''
      this.formData.classification = ''
      this.formData.warehouse = ''
      this.formData.quantity = ''
      this.formData.basicprice = ''
      this.propertyList = [
        {
          id: 1,
          propertyName: '',
          inputVisible: false,
          propertyValues: []
        }
      ]
      this.productFiles = []
      this.files = []
    },
    // 商品封面图
    getProcuctFileName (filename) {
      this.productFiles.push(filename)
    },
    // 获取已经上传成功的图片name
    getFileName (filename) {
      this.files.push(filename)
    },
    // 删除商品图片
    removefilePct (filename) {
      this.productFiles = this.productFiles.filter((item) => item !== filename)
    },
    // 删除详情图片
    removeFile (filename) {
      this.files = this.files.filter((item) => item !== filename)
    },

    // 此函数为新增属性，新增就是往this.AttrList数组中添加一个新的对象。
    addAttr () {
      this.propertyList.push({
        id: ++this.id,
        propertyName: '',
        inputVisible: false,
        propertyValues: []
      })
      // this.AttrList.push({
      //   attributeName: '',

      //   imageNeed: 0,
      //   categoryId: this.categoryId
      // })
    },

    // 此函数是跟tag组件绑定的，也就是当tag组件中内容发生改变时，需要将此页面中的数据也相应的进行改变，因为所有的接口都是当前页面进行处理的。
    changeData (obj) {
      for (var i = 0; i < this.AttrList.length; i++) {
        if (this.AttrList[i].id === obj.id) {
          Object.assign(this.AttrList[i], obj)
        }
      }
    },

    // 标签
    handleClose (tag, index) {
      this.propertyList[index].propertyValues.splice(
        this.propertyList[index].propertyValues.indexOf(tag),
        1
      )
    },
    // 删除属性
    removeProperty (index) {
      this.propertyList.splice(index, 1)
    },

    // 商品添加属性
    showInput (index, event) {
      this.propertyList[index].inputVisible = true

      this.$nextTick((_) => {
        console.log(document.querySelector('.input-new-tag').children[0])

        document.querySelector('.input-new-tag').children[0].focus()
      })
    },

    // 允许自定义添加新的选项
    handleInputConfirm (index) {
      const inputValue = this.inputValue

      // console.log(this.inputValue)
      // console.log(
      //   this.propertyList[index].propertyValues.every(
      //     (item) => item.value !== inputValue
      //   )
      // )
      if (
        inputValue &&
        this.propertyList[index].propertyValues.every(
          (item) => item.value !== inputValue
        )
      ) {
        this.propertyList[index].propertyValues.push({
          value: inputValue,
          price: ''
        })
      }
      this.propertyList[index].inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style lang='scss' scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
// .el-select .el-input__inner{
//   width: 800px;
// }

.box-card {
  width: 1245px;
  height: 455px;
}
.card-specification {
  min-height: 400px;
  width: 1245px;
}
.card-particulars {
  min-height: 300px;
  width: 1245px;
}
.details {
  height: 250px;
  width: 1100px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.pct-property {
  padding-left: 100px;
  margin-bottom: 28px;

  // border: 1px solid;
}
.add-property {
  // margin-top: 20px;
  margin-left: 100px;
}
.delete-property {
  margin-left: 20px;
}
.price-right {
  width: 80px;
  height: 32px;
  margin-right: 5px;
  input.el-input__inner {
    height: 32px;
  }
}
</style>
